local msg = require "mp.msg"

local opts = {
    properties = "volume,sub-scale",
}(require 'mp.options').read_options(opts, "save_properties")

local function explode(s, delimiter)
    local result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end

PropertyList = explode(opts.properties, ",")
ConfigDir=os.getenv("HOME") .. "/.config/mpv/"

local function onStartup()
	local file = io.open(ConfigDir .. "saved_properties", "r")
	if file == nil then
		return
	end
	local line = file:read()
	while line ~= nil and line ~= false and line ~= "" do
		PropertyPair=explode(line, "=")
		if not mp.set_property(PropertyPair[1], PropertyPair[2]) then
			msg.log("warning", "Could not set Property " .. PropertyPair[1] .. " to " .. PropertyPair[2])
		end
		line = file:read()
	end
	file:close()
end

local function onShutdown()
	local file = io.open(ConfigDir .. "saved_properties", "w")
	for i in pairs(PropertyList) do
		file:write(PropertyList[i] .. "=" .. mp.get_property(PropertyList[i]) .. "\n")
	end
	file:close()
end

onStartup()
mp.register_event("shutdown", function()
        onShutdown()
end)
